package com.jovision.sovplay;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.entity.StreamFile;
import com.jovision.AppConsts;
import com.jovision.JVNetConst;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * Created by juyang on 16/12/12.
 */

public class JVCatFileListActivity extends BaseActivity {

    private static final String TAG = "JVCatFileListActivity";
    public static final int FLAG_DOWNLOAD_FILE = 0x01113;//录像下载

    private final int IMAGE_FLAG = 1;
    private final int VIDEO_FLAG = 2;

    //variable
    private Calendar rightNow = Calendar.getInstance();
    private int year;
    private int month;
    private int day;
    private int mediaKind;
    private int window;
    private CatFileAdapter catFileAdapter;
    private ArrayList<StreamFile> fileList;
    private int hasDownLoadSize = 0;// 已下载文件大小
    private int downLoadFileSize = 0;// 下载文件大小


    // view
    private EditText selectDateET;// 选择的日期
    private ImageView moreDataIV;// 下三角
    private ListView fileListView;
    private TextView downloadProTV;//下载进度


    @Override
    protected void initSettings() {
        mediaKind = getIntent().getIntExtra("mediaKind", 1);
        window = getIntent().getIntExtra("window", 1);
    }

    @Override
    protected void initUi() {
        setContentView(R.layout.activity_remotelist);

        selectDateET = (EditText) findViewById(R.id.datetext);
        moreDataIV = (ImageView) findViewById(R.id.dateselectbtn);
        selectDateET.setInputType(InputType.TYPE_NULL);
        selectDateET.setOnTouchListener(onTouchListener);
        selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, month, day));
        downloadProTV = (TextView) findViewById(R.id.download_process);
        moreDataIV.setOnTouchListener(onTouchListener);
        catFileAdapter = new CatFileAdapter(this);

        fileListView = (ListView) findViewById(R.id.videolist);
        fileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (mediaKind) {
                    case IMAGE_FLAG: {
                        //TODO
                        break;
                    }
                    case VIDEO_FLAG: {
                        Intent fileIntent = new Intent();
                        fileIntent.setClass(JVCatFileListActivity.this, JVCatFilePlayActivity.class);
                        fileIntent.putExtra("window", window);
                        fileIntent.putExtra("playPath", fileList.get(i).getFilePath());
                        JVCatFileListActivity.this.startActivity(fileIntent);
                        break;
                    }
                    default:
                        break;
                }
            }
        });

        year = rightNow.get(Calendar.YEAR);
        month = rightNow.get(Calendar.MONTH) + 1;
        day = rightNow.get(Calendar.DAY_OF_MONTH);
        selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, month, day));

        searchRemoteFileList(year, month, day);
    }


    /**
     * 查询文件列表
     *
     * @param year
     * @param month
     * @param day
     */
    public void searchRemoteFileList(int year, int month, int day) {
        switch (mediaKind) {
            case IMAGE_FLAG: {
                SovUtil.checkStreamRemoteImage(window, year, month, day);
                break;
            }
            case VIDEO_FLAG: {
                SovUtil.checkStreamRemoteVideo(window, year, month, day);
                break;
            }
            default:
                break;
        }
    }


    /**
     * 日历轻触事件
     */
    View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            if (MotionEvent.ACTION_DOWN == arg1.getAction()) {
                new DatePickerDialog(JVCatFileListActivity.this,
                        new DatePickerDialog.OnDateSetListener() {

                            public void onDateSet(DatePicker arg0, int year,
                                                  int month, int day) {
                                selectDateET.setText(String.format(AppConsts.FORMAT_DATE, year, ++month, day));
                                searchRemoteFileList(year, ++month, day);
                            }
                        }, rightNow.get(Calendar.YEAR),
                        rightNow.get(Calendar.MONTH),
                        rightNow.get(Calendar.DAY_OF_MONTH)).show();
            }
            return true;
        }

    };

    /**
     * 查询文件列表
     * @param view
     */
    public void searchFile(View view) {
        searchRemoteData();
    }

    /**
     * 取消下载
     * @param view
     */
    public void cancelDownload(View view){
        SovUtil.cancelStreamDownload(window);
    }


    /**
     * 检索远程回放数据
     */
    public void searchRemoteData() {
        String temStr = selectDateET.getText().toString();
        String[] temArray = temStr.split("-");
        year = Integer.parseInt(temArray[0]);
        month = Integer.parseInt(temArray[1]);
        day = Integer.parseInt(temArray[2]);
        searchRemoteFileList(year, month, day);
    }

    @Override
    protected void saveSettings() {

    }

    @Override
    protected void freeMe() {

    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
    }

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            //连接结果,视频异常断开时关闭此界面
            case JVNetConst.CALL_CATEYE_CONNECTED: {
                if (arg2 != JVNetConst.CCONNECTTYPE_CONNOK) {
                    this.finish();
                }
                break;
            }
            //开始文件下载
            case FLAG_DOWNLOAD_FILE: {
                if (arg1 <= fileList.size()) {
                    Toast.makeText(JVCatFileListActivity.this, "开始下载第" + arg1 + "个文件", Toast.LENGTH_SHORT).show();
                    switch (mediaKind) {
                        case IMAGE_FLAG: {
                            SovUtil.setDownloadFilePath(window, AppConsts.DOWNLOAD_PATH + arg1 + ".jpg");
                            break;
                        }
                        case VIDEO_FLAG: {
                            SovUtil.setDownloadFilePath(window, AppConsts.DOWNLOAD_PATH + arg1 + ".mp4");
                            break;
                        }
                        default:
                            break;
                    }
                    Log.e(TAG, "downPath=" + fileList.get(arg1).getFilePath());
                    SovUtil.startStreamCatDownload(window, fileList.get(arg1).getFilePath());
                } else {
                    Toast.makeText(JVCatFileListActivity.this, "index大于列表大小，index=" + arg1 + ";size=" + fileList.size(), Toast.LENGTH_SHORT).show();
                }

                break;
            }
            //流媒体猫眼，设置协议回调
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                try {
                    JSONObject object = new JSONObject(obj.toString());
                    int nType = object.getInt("nPacketType");
                    int nCmd = object.getInt("nCmd");
                    switch (nCmd) {
                        //远程视频，图像查询结果
                        case JVNetConst.SRC_REMOTE_CHECK: {
                            //视频文件
                            if (nType == JVNetConst.SRC_EX_CHECK_VIDEO) {
                                String videoData = object.getString("data");
                                fileList = SovUtil.getStreamCatFileList(videoData, selectDateET.getText().toString());
                            } else if (nType == JVNetConst.SRC_EX_CHECK_PCITURE) {//照片文件
                                String imageData = object.getString("data");
                                fileList = SovUtil.getStreamCatFileList(imageData, selectDateET.getText().toString());
                            }
                            if (null == fileList || 0 == fileList.size()) {
                                Toast.makeText(this, "暂无文件", Toast.LENGTH_LONG).show();
                            }
                            catFileAdapter.setData(fileList);
                            fileListView.setAdapter(catFileAdapter);
                            break;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            // 下载进度
            case JVNetConst.CALL_DOWNLOAD: {
                switch (arg2) {
                    //文件头回调
                    case JVNetConst.DT_FILE_HEAD: {
                        //file_length
                        Log.e(TAG, "DOWNLOAD_FILE-DT_FILE_HEAD:obj=" + obj.toString());
                        try {
                            com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                            downLoadFileSize = data.getInteger("file_length");
                            downloadProTV.setText("开始下载-文件总大小：" + downLoadFileSize);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (downLoadFileSize <= 0) {
                            downLoadFileSize = 0;
                            downloadProTV.setText("下载失败：文件大小获取失败" + downLoadFileSize);
                            Toast.makeText(JVCatFileListActivity.this, "下载失败：文件大小获取失败", Toast.LENGTH_LONG).show();
                        }

                        break;
                    }
                    //文件数据回调
                    case JVNetConst.DT_FILE_DATA: {
                        Log.e(TAG, "DOWNLOAD_FILE-DT_FILE_DATA:arg1=" + arg1);

                        if (downLoadFileSize == 0) {
                            Toast.makeText(JVCatFileListActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                            SovUtil.cancelStreamDownload(window);
                            break;
                        } else {
                            try {
                                com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                                int dataLen = data.getInteger("data_len");
                                hasDownLoadSize += dataLen;
                                downloadProTV.setText("下载中-文件总大小：" + downLoadFileSize + "；已下载：" + hasDownLoadSize +"；进度："+ (int) ((float) hasDownLoadSize / downLoadFileSize * 100) + "%");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        break;
                    }
                    case JVNetConst.DT_FILE_TAIL: {
                        com.alibaba.fastjson.JSONObject data = JSON.parseObject(obj.toString());
                        int result = data.getInteger("result");

                        if(result == 1){
                            downloadProTV.setText("下载完成");
                            Toast.makeText(JVCatFileListActivity.this, "下载完成", Toast.LENGTH_LONG).show();
                        }else{
                            downloadProTV.setText("下载失败");
                            Toast.makeText(JVCatFileListActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                        }
                        break;
                    }
                }
                break;
            }
            default:
                break;
        }

    }
}
